﻿using System;
using System.Globalization;
using System.Windows.Data;
using JY.Common.Extensions;

namespace JY.Wpf.Core.Converters
{
    /// <summary>
    /// 四舍五入转换器
    /// </summary>
    public class KeepDigitsConverter : IMultiValueConverter
    {
        /// <summary>
        /// 四舍五入转换器
        /// <MultiBinding Converter="{StaticResource KeepDigitsConverter}">
        ///     <Binding ElementName = "BalanceControl" Path="OptimalRangeEndValue"/>
        ///     <Binding ElementName = "BalanceControl" Path="KeepDigits"/>
        /// </MultiBinding>
        /// </summary>
        /// <param name="values">要保留小数位数的值</param>
        /// <param name="targetType"></param>
        /// <param name="parameter">小数位数</param>
        /// <param name="culture"></param>
        /// <returns></returns>
        public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
        {
            decimal result = 0;
            int keepDigits = 3;

            if (values != null&& values.Length==2)
            {
                if(values[0]!=null)
                {
                    decimal.TryParse(values[0].ToString(), out result);
                }
                if(values[1] != null)
                {
                    int.TryParse(values[1].ToString(), out keepDigits);
                }
            }
            return result.KeepDigits(keepDigits).ToString("f" + keepDigits);
        }

        public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
        {
            string[] splitValues = ((string)value).Split(' ');
            return splitValues;
        }
    }
}
